<template>
  <a-modal
    unmount-on-close
    title-align="start"
    width="50%"
    title="确认报废"
    :visible="modalVisible"
    @ok="handleOk"
    @cancel="handleCancel"
    :mask-closable="false"
  >
    <template #title>
      {{ type === 1 ? '报废申请' : '确认报废' }}
    </template>
    <div style="height: 380px; overflow;: auto">
      <div class="content">
        <div>
          <!-- form表单设置auto-label-width开启自动标签宽度 -->
          <a-form
            :model="currForm.list"
            ref="formRules"
            direction="vertical"
            auto-label-width
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="equipNumber" label="设备编码：" required>
                  <a-input
                    placeholder="请输入设备编码"
                    size="large"
                    v-model="props.form.deviceCoding"
                    disabled
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item field="number" label="设备名称：">
                  <a-input
                    placeholder="系统自动生成"
                    size="large"
                    v-model="props.form.deviceName"
                    disabled
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item label="报废申请时间：" required>
                  <a-date-picker
                    style="width: 100%"
                    show-time
                    format="YYYY-MM-DD HH:mm:ss"
                    :default-value="new Date()"
                    value-format="x"
                    disabled
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="报废申请人：" required>
                  <a-input
                    placeholder="报废申请人"
                    size="large"
                    v-model="info.name"
                    disabled
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="24" class="dept">
                <a-form-item field="scrappedReason" label="报废原因：">
                  <a-textarea
                    :disabled="type !== 1"
                    placeholder="请输入"
                    allow-clear
                    show-word-limit
                    :auto-size="{
                      minRows: 5,
                    }"
                    :max-length="300"
                    v-model="currForm.list.scrappedReason"
                  />
                </a-form-item>
              </a-col>
            </a-row>
            <a-row :gutter="16">
              <a-col :span="24" class="dept">
                <a-form-item field="description" label="图片上传：">
                  <UploadFile
                    :disabled="type !== 1"
                    :file-type-list="['JPEG', 'JPG', 'PNG', 'GIF', 'SVG']"
                    style="margin-top: 20px"
                    ref="refUploadFile"
                    v-model:fileList="equipmentPictures"
                    listType="picture-card"
                    :limit="0"
                    :args="{
                      download: true,
                    }"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
        <div v-if="type !== 1">
          <!-- form表单设置auto-label-width开启自动标签宽度 -->
          <a-form
            ref="formRules"
            :model="currForm.list"
            direction="vertical"
            auto-label-width
          >
            <a-row :gutter="16">
              <a-col :span="12">
                <a-form-item field="status" label="确认结果：">
                  <a-radio-group
                    :default-value="2"
                    v-model="currForm.list.status"
                    :disabled="type === 3"
                  >
                    <a-radio :value="2">是</a-radio>
                    <a-radio :value="1">否</a-radio>
                  </a-radio-group>
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="24">
              <a-col :span="24" class="dept">
                <a-form-item field="remark" label="确认备注：">
                  <a-textarea
                    placeholder="请输入"
                    :disabled="type === 3"
                    allow-clear
                    show-word-limit
                    :auto-size="{
                      minRows: 5,
                    }"
                    v-model="currForm.list.remark"
                  />
                </a-form-item>
              </a-col>
            </a-row>

            <a-row :gutter="16">
              <a-col :span="12" class="dept">
                <a-form-item field="confirmAt" label="确认时间：" required>
                  <a-date-picker
                    style="width: 100%"
                    show-time
                    :disabled="type === 3"
                    format="YYYY-MM-DD HH:mm"
                    v-model="currForm.list.confirmAt"
                    value-format="timestamp"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="确认人：" required>
                  <a-input
                    :disabled="type === 3"
                    style="width: 100%"
                    placeholder="报废申请人"
                    v-model="info.name"
                  />
                </a-form-item>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </div>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
  import { reactive, computed, ref, watchEffect, onMounted, watch } from 'vue';
  import { cloneDeep, filter } from 'lodash';
  import {
    PostEquipmentScrapped,
    PutEquipmentScrapped,
  } from '@/api/equipment-management/base-setting/index';
  import { PutEquipment } from '@/api/equipment-management/equipment-list';
  import { Message } from '@arco-design/web-vue';

  const emit = defineEmits(['update:visible']);
  const info = JSON.parse(sessionStorage.getItem('loginInfo') as string);

  const props = withDefaults(
    defineProps<{
      visible: boolean; // 是否显示对话框
      form: any; // 传进来的数据
      type: 1 | 2 | 3;
      fn?: any;
    }>(),
    {
      visible: false,
    }
  );
  const currForm = reactive<any>({
    list: { equipmentPictures: [] },
  });
  const modalVisible = computed({
    get() {
      return props.visible;
    },
    set(visible: boolean) {
      emit('update:visible', visible);
    },
  });

  watch(modalVisible, (newVal, oldVal) => {
    // 如果newVal为true
    if (newVal) {
      let { form } = props;
      if (props.type === 1) {
        const { id: equipmentId } = form;
        form = { equipmentId, applicant: info.name };
      }
      currForm.list = cloneDeep(form);
    }
  });
  const handleOk = async () => {
    try {
      if (currForm.list.scrappedPictures) {
        currForm.list.scrappedPictures = currForm.list.scrappedPictures.map(
          ({ url, name }: any) => ({
            url,
            name,
          })
        );
      }
      if (props.type === 1) {
        await PostEquipmentScrapped(currForm.list);
      } else if (props.type === 2) {
        currForm.list.confirmer = info.name;
        const { id, status, remark, confirmAt, confirmer } = currForm.list;
        await PutEquipmentScrapped({
          id,
          status,
          remark,
          confirmAt,
          confirmer,
        });
        if (status === 2) {
          await PutEquipment({ id: currForm.list.equipmentId, useState: 7 });
        }
      }
      if (props.fn) {
        props.fn.loadData();
      }
      modalVisible.value = false;
    } catch (error) {
      console.log(error);
      Message.error('服务器问题请联系管理员');
    }
    currForm.list = {};
  };
  let equipmentPictures = computed({
    get() {
      if (
        Array.isArray(currForm.list.scrappedPictures) &&
        currForm.list.scrappedPictures[0] &&
        currForm.list.scrappedPictures[0].url
      ) {
        return currForm.list.scrappedPictures.map((element: any) => {
          return {
            ...element,
            fileUrl: element.url ? element.url : element.sourceAddr,
            fileName: element.name,
            sourceAddr: element.sourceAddr,
          };
        });
      } else {
        return [];
      }
    },
    set(val: any[]) {
      currForm.list.scrappedPictures = val.map((element) => {
        return {
          ...element,
          files: element.fileUrl,
          url: element.sourceAddr,
          name: element.fileName,
        };
      });
    },
  });
  // 取消
  const handleCancel = () => {
    modalVisible.value = false;
    currForm.list = {};
  };
</script>

<style lang="less" scoped></style>
